package com.market.plus.controller;

import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.market.plus.controller.mapper.JsonMapping;
import com.market.plus.core.dto.AvatarDto;
import com.market.plus.core.dto.NewsDto;
import com.market.plus.core.dto.ParticipantDto;
import com.market.plus.core.service.NewsService;
import com.market.plus.core.service.ParticipantService;
import com.market.plus.core.service.ProcessGuestService;
import com.market.plus.core.util.MarketUtil;

@Controller
public class GuestController {

   private ProcessGuestService processGuestService;

   public static final String GUEST_PAGE = "participant/guest";

   private JsonMapping jsonMapping;

   @Autowired
   public GuestController(@Qualifier("processGuestService") ProcessGuestService processGuestService,
      @Qualifier("participantService") ParticipantService participantService,
      @Qualifier("newsService") NewsService newsService,
      @Qualifier("jsonMapping") JsonMapping jsonMapping) {
      this.processGuestService = processGuestService;
      this.jsonMapping=jsonMapping;
   }

   @RequestMapping(value = "/guest", method = RequestMethod.GET)
   public String viewInfo(ModelMap model) {
      ParticipantDto participantDto = MarketUtil.getCurrentView();
      if (participantDto == null){
         return "redirect:/auth/viewInfo";
      }
      List<ParticipantDto> myFriends = this.processGuestService.listFriends();
      NewsDto newsDto = this.processGuestService.getPersonalIntroduction();
      JSONObject jsonObject = jsonMapping.convert(participantDto, newsDto, true);
      model.addAttribute("displayName", jsonObject.getString("nickname"));
      model.addAttribute("participantJSON", jsonObject);
      model.addAttribute("partId", participantDto.getId());
      AvatarDto avatarDto = participantDto.getAvatar();
      model.addAttribute("avatarGUID", (avatarDto == null)?"0":avatarDto.getContentFile().getGuid());
      model.addAttribute("friends", myFriends);
      return GUEST_PAGE;
   }

   @RequestMapping(value = "/guest/news/common", method = RequestMethod.GET)
   public @ResponseBody JSONArray getNews() throws Exception {
      List<NewsDto> newsDtos = this.processGuestService.getNews();
      if (newsDtos == null)
         newsDtos = new ArrayList<NewsDto>();
      JSONArray jsonArray = this.jsonMapping.convertNews(newsDtos);
      return jsonArray;
   }
}
